package com.miexiaoliang.springbootshiro;

import java.time.LocalDateTime;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController extends BaseController {

    @RequestMapping("/loginPage")
    public String loginPage() {
        System.out.println("用户登录页");
        return "用户登录页";
    }

    @RequestMapping("/login")
    public String login(String userName, String password) {
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        Subject subject = getSubject();
        try {
            // 若用户已经登录，则先登出，再重新登录
            if (subject.isAuthenticated()) {
                subject.logout();
            }
            subject.login(token);
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }

        System.out.println("登录成功! user: " + subject.getPrincipal());
        return "登录成功! user: " + subject.getPrincipal() + ", loginTime: " + LocalDateTime.now().toString();
    }

    /**
     * 这个方法用户【有权限】可以访问
     */
    @RequiresPermissions("user:list")
    @RequestMapping("/test")
    public String test() {
        System.out.println("当前用户 id: " + getcurrentUserId());
        return "当前用户 id: " + getcurrentUserId();
    }

    /**
     * 这个方法用户【没权限】可以访问
     */
    @RequiresPermissions("zoo:insert")
    @RequestMapping("/try")
    public String tryPermission() {
        return "看到这句话时，说明你的代码有问题";
    }

}